<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\model\OrderVideo;
use app\common\model\User;
use app\common\model\UserLevelVideo;
use app\common\tool\account\Account;
use app\common\model\Account as AccountModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class VideoReferrerAward
{
    /**
     * 视频推荐奖（充值后返）
     * @param $data
     */
    public function handle($order)
    {
        try{
            if($puid = User::where('id',$order->uid)->value('parent_id')){

                $amount = confValue('video_direct_award');//自身未充值视频会员，每推荐一人充值可获得50红包币，不计入看视频奖励封顶
                Account::getInstance()->basics($puid, 'red_coin', $amount , '视频充值推荐奖励得积分', '+')->setOrder($order->id)->createBonus($order->uid,AccountModel::VIDEO_DIRECT);

                $puser = User::where('id',$puid)->field('id,level_video_id')->find();
                if($puser && $puser->level_video_id){

                    $level = UserLevelVideo::column('direct_red_coin', 'id');
                    $porder = OrderVideo::where(['uid'=>$puid,'status'=>1])->field('id,red_coin,max_red_coin')->find();
                    if($porder){
                        $red_coin = $level[$puser->level_video_id];

                        if($porder->red_coin + $red_coin > $porder->max_red_coin){
                            $red_coin = roundNum($porder->max_red_coin - $porder->red_coin);
                        }

                        $porder->red_coin += $red_coin;
                        $porder->save();

                        $puser->assets->video_reward_surplus -= $red_coin;
                        $puser->assets->save();
                        Account::getInstance()->basics($puid, 'red_coin', $red_coin, '视频充值推荐奖励得积分加速', '+')->createBonus($order->uid,AccountModel::VIDEO_DIRECT);
                    }
                }
            }
        }catch (\Exception $e){
            Log::write("listener.VideoReferrerAward:".$e->getMessage());
            throw new Exception("加载失败：".$e->getMessage(), -1);
        }

    }

}